﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using FacebookApp;

public partial class Pages_Order : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["Cart"] != null)
            {
                var dtshow = new DataTable();
                dtshow = (DataTable)Session["Cart"];
                if (dtshow.Rows.Count == 0)
                {
                    btndathang.Enabled = false;
                }
                else
                {
                    btndathang.Enabled = true;
                }
                rptOrder.DataSource = dtshow;
                rptOrder.DataBind();
                TinhTien();
            }
            else
            {
                DataTable dtshoppingcart;
                dtshoppingcart = new DataTable("Shoppingcart");
                dtshoppingcart.Columns.Add("ProductID", typeof(String));
                dtshoppingcart.Columns.Add("ProductName", typeof(String));
                dtshoppingcart.Columns.Add("Price", typeof(String));
                dtshoppingcart.Columns.Add("Quantity", typeof(String));
                dtshoppingcart.Columns.Add("Total", typeof(String));
                rptOrder.DataSource = dtshoppingcart;
                rptOrder.DataBind();
                btndathang.Visible = false;
                //Response.Redirect("/");
            }
            pnOrder.Visible = true;
            Successfull.Visible = false;
        }
    }
    protected void rptOrder_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string strCA = e.CommandArgument.ToString();
        switch (e.CommandName)
        {
            case "Update":
                Label lblProductID;
                Label lbltotal;                
                for (int i = 0; i < rptOrder.Items.Count; i++)
                {
                    lblProductID = (Label)rptOrder.Items[i].FindControl("lblproductid");
                    if (lblProductID.Text.Trim().Equals(strCA))
                    {
                        var lblprice = (Label)rptOrder.Items[i].FindControl("lblprice");
                        var quantitytext = (TextBox)rptOrder.Items[i].FindControl("txtquantity");
                        string quantity = EbookService.Ebook_GetById(((Label)rptOrder.Items[i].FindControl("lblproductid")).Text).Quantity.ToString();
                        lbltotal = (Label)rptOrder.Items[i].FindControl("lbltotal");
                        lblprice.Text = lblprice.Text.Substring(0, lblprice.Text.LastIndexOf("VNĐ"));
                        lblprice.Text = lblprice.Text.Replace(".", "");
                        try
                        {
                            if (Int32.Parse(quantitytext.Text) > Int32.Parse(quantity))
                            {
                                quantitytext.Text = quantity;
                            }

                            lbltotal.Text = Format_Price((Int32.Parse(lblprice.Text) * Int32.Parse(quantitytext.Text)).ToString());
                        }
                        catch
                        {
                            quantitytext.Text = "1";
                            lbltotal.Text = Format_Price(lblprice.Text);
                        }
                        lblprice.Text = lblprice.Text + " VNĐ";
                        Cart_UpdateNumber((DataTable)Session["Cart"], strCA, quantitytext.Text);
                    }

                }
                Response.Redirect(Request.Url.LocalPath);

                break;
            case "Delete":

                var dtdelete = new DataTable();
                dtdelete = (DataTable)Session["Cart"];
                for (int i = 0; i < dtdelete.Rows.Count; i++)
                {
                    if (dtdelete.Rows[i]["ProductID"].ToString().Equals(strCA))
                    {
                        //int totalcount = int.Parse(Session["_countPro"].ToString());
                        //totalcount -= int.Parse(dtdelete.Rows[i]["Quantity"].ToString());
                        //Session["_countPro"] = totalcount;
                        dtdelete.Rows.RemoveAt(i);
                    }
                }
                Response.Redirect(Request.Url.LocalPath);
                break;
        }
        TinhTien();
    }
    public void Cart_UpdateNumber(DataTable cartdetail, string proid, string inumber)
    {
        if (cartdetail.Rows.Count > 0)
        {
            //int countPro = 0;
            for (int i = 0; i < cartdetail.Rows.Count; i++)
            {
                if (cartdetail.Rows[i]["ProductID"].ToString().Equals(proid))
                {
                    cartdetail.Rows[i]["Quantity"] = inumber;
                    // update money
                    cartdetail.Rows[i]["Total"] = Convert.ToInt32(inumber) *
                                                  Convert.ToDouble(cartdetail.Rows[i]["Price"].ToString());
                    break;
                }
               // countPro += int.Parse(cartdetail.Rows[i]["Quantity"].ToString());
            }
            //Session["_countPro"] = countPro;
        }
    }
    public void TinhTien()
    {
        try
        {
            int totalprice = 0;
            for (int i = 0; i < rptOrder.Items.Count; i++)
            {
                var lbltotalprice = (Label)rptOrder.Items[i].FindControl("lbltotal");
                lbltotalprice.Text = lbltotalprice.Text.Substring(0, lbltotalprice.Text.LastIndexOf(" VNĐ"));
                lbltotalprice.Text = lbltotalprice.Text.Replace(".0000", "");
                lbltotalprice.Text = lbltotalprice.Text.Replace(".", "");
                lbltotalprice.Text = lbltotalprice.Text.Replace(",", "");
                totalprice += Int32.Parse(lbltotalprice.Text);
                lbltotalprice.Text = Format_Price(lbltotalprice.Text);
            }
            if (totalprice == 0)
                btndathang.Visible = false;
            lbltongtien.Text = "Tổng tiền :" + " " + Format_Price(totalprice.ToString());
            Session["totalprice"] = totalprice.ToString();
        }
        catch (Exception)
        {
            lbltongtien.Text = "Số lượng quá lớn - Vui lòng cập nhật lại số lượng.";
            btndathang.Enabled = false;
        }

    }

    protected string Format_Price(string s)
    {
        return FunctionClass.Format_Price(s);
    }

    protected void btndathang_Click(object sender, ImageClickEventArgs e)
    {
       // int sessiontotalprice = 0;
       // string MailBody = "Sản phẩm đặt mua:\n";
       // for (int i = 0; i < rptOrder.Items.Count; i++)
       // {
       //     var lblProductName = (Label)rptOrder.Items[i].FindControl("lblProductName");
       //     var txtQuantity = (TextBox)rptOrder.Items[i].FindControl("txtquantity");
       //     var lbltotalprice1 = (Label)rptOrder.Items[i].FindControl("lbltotal");
       //     MailBody += "\t" + lblProductName.Text + " --- Số lượng: " + txtQuantity.Text + " --- Thành tiền: " + lbltotalprice1.Text + "\n";
       //     lbltotalprice1.Text = lbltotalprice1.Text.Substring(0, lbltotalprice1.Text.LastIndexOf("VNĐ"));
       //     lbltotalprice1.Text = lbltotalprice1.Text.Replace(".", "");
       //     sessiontotalprice += Int32.Parse(lbltotalprice1.Text);

       // }
       // MailBody += "Tổng tiền: " + Format_Price(sessiontotalprice.ToString());
       //// Session["totalprice"] = sessiontotalprice.ToString();
       // if (Session["UserName"] == null)
       // {
            Session["rptOrder"] = rptOrder;
            Response.Redirect("/Pages/RegisterOrder.aspx");
        //}
        //else
        //{
        //    try
        //    {
        //        //Save_Order();
        //        //string Mail = UserService.User_GetById(Session["UserName"].ToString()).Rows[0]["Mail"].ToString();
        //        SendMail.Mail("Mail", MailBody, "Thông báo đơn đặt hàng");
        //    }
        //    catch
        //    {
        //        Response.Redirect("/Pages/Error.aspx");
        //    }
        //    pnOrder.Visible = false;
        //    Successfull.Visible = true;
        //}
    }

    protected void btnmuatiep_Click2(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("/");
    }

    //public void Save_Order()
    //{
    //    try
    //    {
    //        Label lblProductID;
    //        Label lbltotal;
    //        TextBox txtQuantity;
    //        string MailBody = "Sản phẩm đặt mua:\n";
    //        for (int i = 0; i < rptOrder.Items.Count; i++)
    //        {
    //            OrderDetailInfo obj1 = new OrderDetailInfo();
    //            var lblProductName = (Label)rptOrder.Items[i].FindControl("lblProductName");
    //            var lbltotalprice1 = (Label)rptOrder.Items[i].FindControl("lbltotal");
    //            lblProductID = (Label)rptOrder.Items[i].FindControl("lblproductid");
    //            lbltotal = (Label)rptOrder.Items[i].FindControl("lbltotal");
    //            txtQuantity = (TextBox)rptOrder.Items[i].FindControl("txtquantity");
    //            MailBody += "\t" + lblProductName.Text + " --- Số lượng: " + txtQuantity.Text + " --- Thành tiền: " + Format_Price(lbltotalprice1.Text) + "\n";
    //            obj1.Order_Id = OrderID;
    //            obj1.Ebook_Id = lblProductID.Text;
    //            obj1.Quantity = txtQuantity.Text;
    //            obj1.Money = lbltotal.Text;
    //            OrderDetailService.OrderDetail_Insert(obj1);
    //        }
    //        MailBody += "Tổng tiền: " + Format_Price(Session["totalprice"].ToString());

    //        SendMail.Mail(txtMail.Text, MailBody, "[eBookStore - Facebook] Thông báo đơn đặt hàng");
    //        //pnRegister.Visible = false;
    //        //pnRegisterSuccessfull.Visible = true;
    //    }
    //    catch (Exception e)
    //    {
    //        WebMsgBox.Show(e.Message);
    //    }
    //}

}